<html>
<head>
<title>Calculator</title>
</head>

<body>
<h1>Calculator</h1>
Victor Perez <br />
Ver 1.0 4/8/2012 <br />
Type a expression to be calculated of the following form (1+2+3).
<p>
<form method="get" action="calculator.php">
<input type="text" name="expr" />
<input type="submit" value="calculate" />
</form>
</p>

<?php
//Get the "expr" input form data
$expr = $_GET["expr"];

//Start by assuming the expression will not be valid
$valid_expr = false;

if ($expr) {
    //Originally tried removing all whitespace characters
    #$expr = preg_replace('/\s/','', $expr );

    /*
     * Regular expression pattern to detect proper mathematical expression.
     * 1. Match to the beginning of the string
     * 2. Zero of more whitespace characters followed by 1 or none negative signs.
     * 3. Followed by zero of more whitespace characters.
     * 4. Followed by 1 or more digits, and 1 or none decimal point followed by 1 or more
     *    digits.
     * 5. Followed by zero or more whitespace characters.
     * 6. a. Followed by a "+","*", or "\", and zero or more whitespace characters.
     *       This followed by 1 or none negative sign.
     *    b. OR followed by a "-", 1 or more whitespace characters, and a "-" charcter.
     *    c. OR followed by a "-".
     * 7. Followed by zero or more whitespace characters.
     * 8. Followed by 1 or more digits, which are additionally followed by 1 or none decimal point
     *    and 1 or more digits.
     * 9. 5-8 repeated 0 or more times, and matching the end of the string.
     */
    $valid_pattern = '/^\s*-?\s*[0-9]+(\.[0-9]+)?(\s*([\+\*\/]\s*-?|\-\s+\-|\-)\s*[0-9]+(\.[0-9]+)?)*$/';

    /*
     * Regular expression to check for division by 0.
     * 1. Match a division sign followed by a 1 or none negative sign.
     * 2. Followed by a "0", which can be followed by a decimal and 1 or more 0's
     * Examples: X/0, X/0.000
     */
    $div0_pattern = '/\/-?[0](\.[0]+)?/';

    //Check if expr is a valid expression
    $valid_expr = preg_match($valid_pattern, $expr);

    //Check if division by 0 is being performed
    $isDiv0 = preg_match($div0_pattern, $expr);

    echo "<b>" . "Result:" . "</b>" . "<br />";
    //If a valid expression was provided...
    if ($valid_expr) {
        if ($isDiv0) {
	    echo $expr . ": Invalid division by 0";
	}
	else {
      	    eval("\$result = $expr;");
            echo $expr . " = " . $result;
        }
    }
    else {
    	//An invalid expression was provided
        echo $expr . ": Expression is not valid";
    }
  }
?>

</body>

</html>
